package com.boilerCloud.service.device.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import redis.clients.jedis.Jedis;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.boilerCloud.dao.device.DeviceDao;
import com.boilerCloud.dto.HzlqswPage;
import com.boilerCloud.dto.device.DeviceInfo;
import com.boilerCloud.dto.sys.ReqResult;
import com.boilerCloud.service.device.IDeviceService;
import com.boilerCloud.util.MD5;
import com.boilerCloud.util.RedisPoolsUtil;
import com.boilerCloud.util.StringUtil;
import com.fbox.Main;
@Service
public class DeviceServiceImpl implements IDeviceService {

	@Resource
	private DeviceDao dao;
	
	@Override
	public void qryList(DeviceInfo device, HzlqswPage<DeviceInfo> page)throws Exception {
		dao.qryList(device,page);
	}

	@Override
	public void edit(DeviceInfo device)throws Exception {
		DeviceInfo orgin = dao.getDeviceInfo(device.getId());
		if(!StringUtil.isEmpty(device.getCommSerialNumber()) && !device.getCommSerialNumber().equals(orgin.getCommSerialNumber())){
			//通讯设备修改了
			JSONObject json = Main.getBoxInfo(device.getCommSerialNumber());
			if(json != null){
				
				String box_id =json.getString("uid");
				if(box_id == null){
					box_id = json.getJSONObject("box").getString("uid");
				}
				int state = json.getJSONObject("box").getJSONObject("commServer").getIntValue("state");
				device.setBoxId(box_id);
				device.setState(state);
			}
		}
		dao.edit(device);
	}

	@Override
	public void delDevice(int id)throws Exception {
		dao.del(id);
		
	}

	@Override
	public void addDevice(DeviceInfo device) throws Exception{
		// TODO Auto-generated method stub
		if(!StringUtil.isEmpty(device.getCommSerialNumber())){
			
			JSONObject json = Main.getBoxInfo(device.getCommSerialNumber());
			if(json != null){
				
				String box_id =json.getString("uid");
				if(box_id == null){
					box_id = json.getJSONObject("box").getString("uid");
				}
				int state = json.getJSONObject("box").getJSONObject("commServer").getIntValue("state");
				device.setBoxId(box_id);
				device.setState(state);
			}
		}
		dao.add(device);
	}

	@Override
	public DeviceInfo getDeviceInfo(int id) throws Exception {
		// TODO Auto-generated method stub
		return dao.getDeviceInfo(id);
	}

	

	/**
	 * <p>Title: bindDeviceProject</p>
	 * <p>Description:(一句话阐述):设备绑定项目操作 </p>
	 * @param device
	 * @author Ran_cc 
	 * @date 2018年3月15日
	 */
	@Override
	public void bindDeviceProject(DeviceInfo device) throws Exception {
		String devs = device.getDeviceIds();
		String [] devarr = devs.split(",");
		DeviceInfo di =null;
		for (int i = 0; i < devarr.length; i++) {
			di = new  DeviceInfo();
			di.setProjectId(device.getProjectId());
			di.setId(Integer.parseInt(devarr[i]));
			dao.edit(di);
		}
		
	}

	/**
	 * <p>Title: celbindDeviceProject</p>
	 * <p>Description:(一句话阐述): 解除绑定</p>
	 * @param device
	 * @throws Exception
	 * @author Ran_cc 
	 * @date 2018年3月16日
	 */
	@Override
	public void celbindDeviceProject(DeviceInfo device) throws Exception {
		dao.edit(device);
		
	}

	@Override
	public Object getDeviceList(int type,DeviceInfo device) throws Exception {
		List<DeviceInfo> list = dao.getDeviceList(device);
		if(list == null){
			return null;
		}
		if(type == 2){
			Map<String,List<DeviceInfo>> map = list.stream().collect(Collectors.groupingBy(DeviceInfo::getUsername));
			return map;
		}
		if(type == 3){
			Map<String,List<DeviceInfo>> map = list.stream().collect(Collectors.groupingBy(DeviceInfo::getModelName));
			return map;
		}
		return null;
	}

	@Override
	public Object getAlarmRecordList(int id,ReqResult rst) throws Exception {
		DeviceInfo orgin = dao.getDeviceInfo(id);
		if(StringUtil.isEmpty(orgin.getBoxId())){
			rst.setResultCode(ReqResult.resultCode_error);
			rst.setReturnObject("未绑定box");
			return null;
		}
		return dao.getAlarmRecordList(orgin.getId());
	}

	@Override
	public Object getCurrentDataList(int id, ReqResult rst) throws Exception {
		DeviceInfo orgin = dao.getDeviceInfo(id);
		if(StringUtil.isEmpty(orgin.getBoxId())){
			rst.setResultCode(ReqResult.resultCode_error);
			rst.setReturnObject("未绑定box");
			return null;
		}
		JSONObject json = new JSONObject();
		String boxId = orgin.getBoxId();
		System.out.println("****"+boxId);
		JSONArray array = Main.hdataitems(boxId);
		JSONArray channels = null;
		List<Long> list = null;
		JSONObject object = null;
		JSONArray rows = null;
		List<String> names = null;//new ArrayList<>();
		List<String> units = null;
		for (int i = 0; i < array.size(); i++) {
			System.out.println("--------"+array.getJSONObject(i));
			channels = array.getJSONObject(i).getJSONArray("channels");
			System.out.println(channels);
			list = new ArrayList<>();
			names = new ArrayList<>();
			units = new ArrayList<>();
			for (int j = 0; j < channels.size(); j++) {
				list.add(channels.getJSONObject(j).getLong("uid"));
				names.add(channels.getJSONObject(j).getString("name"));
				units.add(channels.getJSONObject(j).getString("unit"));
			}
			object = Main.hdata(list.toArray(new Long[0]));
			System.out.println("/////////"+object);
			rows = object.getJSONArray("rows");//
			System.out.println("==="+rows.getJSONObject(rows.size()-1).get("c"));
			System.out.println("==="+rows.getJSONObject(rows.size()-1).getJSONArray("c"));
			rows = rows.getJSONObject(rows.size()-1).getJSONArray("c");
			for (int j = 0; j < rows.size(); j++) {
				//json.put(names.get(j), rows.get(j)+units.get(j));
				json.put(MD5.getMD5(names.get(j)), names.get(j)+ "_" + rows.get(j)+units.get(j));
			}
		}
		Jedis jedis = RedisPoolsUtil.getInstance().getResource();
		String key = "boxid_" + boxId;
		if(jedis.get(key) != null){
			object = JSONObject.parseObject(jedis.get(key));
			object.putAll(json);		
   		}
		else{
			object = json;
		}
		jedis.set(key, object.toJSONString());
		if(jedis != null){
			jedis.close();
		}
		return object;
	}

	@Override
	public Object getHistoryDataList(int id, long channel, ReqResult rst) throws Exception {
		DeviceInfo orgin = dao.getDeviceInfo(id);
		if(StringUtil.isEmpty(orgin.getBoxId())){
			rst.setResultCode(ReqResult.resultCode_error);
			rst.setReturnObject("未绑定box");
			return null;
		}
		JSONObject json = null;
		String boxId = orgin.getBoxId();
		//
		JSONArray array = Main.hdataitems(boxId);
		JSONArray channels = null;
		List<Long> list = null;
		JSONObject object = null;
		JSONArray rows = null;
	//	JSONArray rows_ = null;
		List<String> names = null;//new ArrayList<>();
		List<String> units = null;
		List<JSONObject> body = new ArrayList<>();
		for (int i = 0; i < array.size(); i++) {
			System.out.println("--------"+array.getJSONObject(i));
			if(array.getJSONObject(i).getLong("uid") != channel) continue;
			channels = array.getJSONObject(i).getJSONArray("channels");
			System.out.println(channels);
			list = new ArrayList<>();
			names = new ArrayList<>();
			units = new ArrayList<>();
			for (int j = 0; j < channels.size(); j++) {
				list.add(channels.getJSONObject(j).getLong("uid"));
				names.add(channels.getJSONObject(j).getString("name"));//列
				units.add(channels.getJSONObject(j).getString("unit"));//单位集合
			}
			System.out.println(list);
			object = Main.hdata(list.toArray(new Long[0]));
			System.out.println("/////////"+object);
			rows = object.getJSONArray("rows");//
			//System.out.println("==="+rows.getJSONObject(rows.size()-1).get("c"));
		//	System.out.println("==="+rows.getJSONObject(rows.size()-1).getJSONArray("c"));
			for (int j = 0; j < rows.size(); j++) {
				//rows_ = rows.getJSONObject(j).getJSONArray("c");//放一行数据
				json = new JSONObject();
				json.put("time", rows.getJSONObject(j).getLongValue("t"));
				json.put("column", rows.getJSONObject(j).getJSONArray("c"));
				/*for (int k = 0; k < rows_.size(); k++) {
					json.put("t"+(k+1), rows.get(k)+units.get(k));
				}*/
				body.add(json);
			}
			/*rows = rows.getJSONObject(rows.size()-1).getJSONArray("c");
			for (int j = 0; j < rows.size(); j++) {
				json.put(names.get(j), rows.get(j)+units.get(j));
			}*/
		}
		json = new JSONObject();
		json.put("header", names);
		json.put("body", body);
		return json;
	}

	@Override
	public Object qryChannel(int id, ReqResult rst) throws Exception {
		DeviceInfo orgin = dao.getDeviceInfo(id);
		if(StringUtil.isEmpty(orgin.getBoxId())){
			rst.setResultCode(ReqResult.resultCode_error);
			rst.setReturnObject("未绑定box");
			return null;
		}
		String boxId = orgin.getBoxId();
		JSONArray array = Main.hdataitems(boxId);
		List<JSONObject> list = new ArrayList<JSONObject>();
		JSONObject json = null;
		for (int i = 0; i < array.size(); i++) {
			json = new JSONObject();
			json.put("uid", array.getJSONObject(i).getString("uid"));
			json.put("name", array.getJSONObject(i).getString("name"));
			list.add(json);
		}
		return list;
	}

	@Override
	public List<String> qryBoxIds() {
		
		try {
			return  dao.qryBoxIds();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return new ArrayList<>();
		}
	}

	@Override
	public void updateState(int state, String box_id) {
		dao.updateState(state,box_id);
	}

	@Override
	public List<DeviceInfo> qrydeviceBoxIds() throws Exception {
		
		return dao.qrydeviceBoxIds();
	}

	@Override
	public void addWarnInfo(JSONArray array, int id) throws Exception {
		if(array != null){
			for (int i = 0; i < array.size(); i++) {
				dao.addWarnInfo(array.getJSONObject(i),id);
				if(array.getJSONObject(i).getIntValue("a") == 3){
					dao.updateShow(array.getJSONObject(i).getIntValue("n"), id);
				}
			}
		}
		
	}

	@Override
	public void updateQueryTime(long time, int id) throws Exception {
		dao.updateQueryTime(time,id);
		
	}

	@Override
	public Object getCurrAlarmRecordList(int id, ReqResult rst)
			throws Exception {
		DeviceInfo orgin = dao.getDeviceInfo(id);
		if(StringUtil.isEmpty(orgin.getBoxId())){
			rst.setResultCode(ReqResult.resultCode_error);
			rst.setReturnObject("未绑定box");
			return null;
		}
		return dao.getCurrAlarmRecordList(id);
	}


}
